//
//  SeeRadioViewController.m
//  Zaker
//
//  Created by lirui on 16/3/11.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "SeeRadioViewController.h"
#import <AVFoundation/AVFoundation.h>

#import "LHAFNetworkTool.h"

@interface SeeRadioViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)NSMutableArray *dataArr;
@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic, retain)UIImageView *topView;
@property(nonatomic,retain)UIImageView *imgView;
@property(nonatomic, retain)NSMutableArray *musArr;
@property(nonatomic, assign)BOOL isPlay;
@property(nonatomic, retain)UIButton *bofang;
@property(nonatomic,assign)NSInteger index;
//@property(nonatomic, retain)PlayerManager *manager;
@property(nonatomic, retain)UIView *naviBar;
@property(nonatomic, retain)UIButton *bofang1;
@property(nonatomic, retain)UISlider *slide;

//包换音频所有数据，图片等等
@property (nonatomic, retain)NSMutableDictionary *dataDic;
//音频网络请求次数
@property (nonatomic, assign)NSInteger number;
@end
@implementation SeeRadioViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
//    _bofang.selected = YES;
    
    
   
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [_tableView removeObserver:self forKeyPath:@"contentOffset"];
    self.tabBarController.tabBar.hidden = NO;
    [_delegate.manager pause];
    

   }
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [ UIColor whiteColor];

    _number = 0;
    self.dataDic = [NSMutableDictionary dictionary];
       [self data];
    [self creatTableView];
    [self creatTopPlayer];
    [self createNaviBar];
    [self loadMBProgress];
   
    
}
-(void)data
{
    NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/%@/0-20.html",_tidString ];
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
      NSArray *arr = resposeObject[_tidString];
        self.dataArr = [SeeRadioModel modelHandlerWithArray:arr];
        
        [_tableView reloadData];
        [self topdata];

       
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
        
}
- (void)topdata {
    
    for (int i = 0 ; i < _dataArr.count; i ++ ) {
        NSString *postId = [_dataArr[i] postid];
        [self data1:postId];
    }
    
}

-(void)data1:(NSString *)audioId {
        NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html",audioId ];
            NSLog(@"mp3Str:%@",str);
         [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
             NSDictionary *dic = resposeObject[audioId];
             NSLog(@"~~~~~~%@",dic);
             NSArray *arr = dic[@"video"];
             self.musArr = [ NSMutableArray array];
             for (NSDictionary *dic1 in arr) {
                 //将所有的音频数据取出
                 [self.dataDic setObject:dic1 forKey:audioId];
             }
             _number += 1;
             if (_dataArr.count == _number) {
                 
                 for (int i = 0 ; i < _dataArr.count; i ++ ) {
                     NSString *postId = [_dataArr[i] postid];
                     NSString *img = self.dataDic[postId][@"cover"];
                     NSString *url = self.dataDic[postId][@"url_m3u8"];
                     [self.imgView sd_setImageWithURL:[NSURL URLWithString:img]];
                     [self.musArr addObject:url];
                 }
                 [self playAudio:self.musArr];
             }
             
             
                [self.hud removeFromSuperview];
             
             if (_delegate.manager.playerState == PlayStatePlay) {
                 _bofang.selected  = YES;
             }
                  if(_delegate.manager.playerState == PlayerStatePause)
             {
                 _bofang.selected = NO;
                 
                             }
             
             
         } failure:^(NSURLSessionDataTask *task, NSError *error) {
             
         }];
}


- (void)playAudio:(NSMutableArray *)urlArr
{
    _delegate = [UIApplication sharedApplication].delegate;
    
    if (_delegate.manager.musicArray == nil) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // something
            _delegate.manager = [PlayerManager defaultManager];
            _delegate.manager.musicArray =[NSMutableArray arrayWithArray:urlArr];
            NSLog(@"arrnew: %@", _delegate.manager.musicArray);
            
            [_delegate.manager play];
         
            [self progressObserving];
        });
    } else {
          _bofang.selected =YES;
        NSMutableArray *tempArr = [NSMutableArray arrayWithArray:_delegate.manager.musicArray];
        NSString *string1 = urlArr[0];
        NSString *string2 = tempArr[0];
        if (![string1 isEqualToString: string2]) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                // something
                _delegate.manager = [PlayerManager defaultManager];
                _delegate.manager.musicArray =[NSMutableArray arrayWithArray:urlArr];
                NSLog(@"arrnew: %@", _delegate.manager.musicArray);
                
                [_delegate.manager play];
              
                [self progressObserving];
            });
            
        } else {
            //音频文件相同
            [self progressObserving];
            
        }
        
    }
    
}

//头部视图
-(void)creatTopPlayer
{
    
   
    self.topView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 375, 250 * HEIGHT)];
    self.topView.backgroundColor = [UIColor lightGrayColor];
    self.tableView .tableHeaderView = self.topView;
    self.topView.userInteractionEnabled = YES;
    self.topView.image = [ UIImage imageNamed:@"beijing"];
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100 * WIDTH, 100 * HEIGHT)];
    self.imgView.center = self.topView.center;
    self.imgView.layer.cornerRadius = self.imgView.frame.size.width / 2;
    self.imgView.clipsToBounds = YES;
//    self.imgView.backgroundColor = [UIColor greenColor];
    [self.topView addSubview:self.imgView];
    self.bofang = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.bofang setImage:[UIImage imageNamed:@"iconfont-zhibo"] forState:UIControlStateNormal];
    [self.bofang setImage:[UIImage imageNamed:@"iconfont-zhibo-1"] forState:UIControlStateSelected];
    self.bofang.selected = NO;
    self.bofang.frame  = CGRectMake(0, 0, 40 * WIDTH, 40 *HEIGHT);
    self.bofang.center = self.topView.center;
    [self.bofang addTarget:self action:@selector(bofangClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.bofang];
    
    UIButton *last = [ UIButton buttonWithType:UIButtonTypeCustom];
    [last setImage:[UIImage imageNamed:@"iconfont-suopingshangyiqu"] forState:UIControlStateNormal];
    last.frame  = CGRectMake(_topView.center.x - 100, self.bofang.center.y - 20, 40 * WIDTH, 40 *HEIGHT);
    
    [last addTarget:self action:@selector(lastClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:last];
    
    UIButton *next = [ UIButton buttonWithType:UIButtonTypeCustom];
    [next setImage:[UIImage imageNamed:@"iconfont-suopingxiayiqu"] forState:UIControlStateNormal];
    next.frame  = CGRectMake(_topView.center.x + 60, self.bofang.center.y -20, 40 * WIDTH, 40 *HEIGHT);
    [next addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:next];
    
    self.slide = [[ UISlider alloc] initWithFrame:CGRectMake(20 * WIDTH, 200 * HEIGHT, WIDTH * (375 - 40), 50 * HEIGHT)];
    [_slide addTarget:self action:@selector(slider:) forControlEvents:UIControlEventValueChanged];
    [self.topView addSubview:_slide];

    
}
#pragma mark -创建tableview
-(void)creatTableView
{
    self.tableView = [[ UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 667) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[BaseTableViewCell class] forCellReuseIdentifier:@"cell"];
    /* KVO */
    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    
    
}
#pragma mark -协议方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}
#pragma mark -cell设置
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath ];
      SeeRadioModel *m = _dataArr[indexPath.row];
    cell.textLabel.text =m.title;
    cell.textLabel.font = [ UIFont systemFontOfSize:14];
    cell.textLabel.numberOfLines = 2;
    cell.textLabel.textColor = [UIColor grayColor];
  cell.selectionStyle = UITableViewCellSelectionStyleNone;
      return  cell;
    
}


#pragma mark -行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(void)bofangClick:(UIButton *)btn
{
     _isPlay =! _isPlay;
    if(!_isPlay){
    
        btn.selected = YES;
        [_delegate.manager play];
      
    
    }else
{
    btn.selected = NO;
    [_delegate.manager pause];
   
}
   


}
-(void)lastClick:(UIButton *)btn1
{
    
    [_delegate.manager lastMusic];
}
-(void)nextClick:(UIButton *)btn1
{
   
    [_delegate.manager nextMusic];
}
-(void)slider:(UISlider *)s
{
    [_delegate.manager pause];
    CGFloat current = s.value *_delegate.manager.totalTime;
    
    [_delegate.manager seekToNewTime:current];
    [_delegate.manager play];
   
  }

-(void)progressObserving{
    __weak SeeRadioViewController *VC = self;
    [self.delegate.manager.avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        if (VC.isPlay) {
            VC.bofang.selected = NO;
        } else {
           VC. bofang.selected = YES;
        }
        VC.slide.value = VC.delegate.manager.currentTime /VC.delegate.manager.totalTime;
        
        if (VC.slide.value == 1) {
            [VC.delegate.manager playerDidFinish];
        }
        
        
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{      _bofang.selected = YES;
    self.index = indexPath.row;
    [_delegate.manager changeMusicWithIndex:self.index];
   
}
- (void)createNaviBar
{
    self.naviBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
    _naviBar.backgroundColor = [UIColor redColor];
    [self.view addSubview:_naviBar];
    _naviBar.alpha = 0;
    
    self.bofang1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [_bofang1 setImage:[UIImage imageNamed:@"iconfont-zhibo"] forState:UIControlStateNormal];
    [_bofang1 setImage:[UIImage imageNamed:@"iconfont-zhibo-1"] forState:UIControlStateSelected];
    _bofang1.selected = NO;
    _bofang1.frame  = CGRectMake(0, 0, 40 * WIDTH, 40 *HEIGHT);
    _bofang1.center = self.naviBar.center;
    [_bofang1 addTarget:self action:@selector(bofangClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.naviBar addSubview:_bofang1];
    
    UIButton *last = [ UIButton buttonWithType:UIButtonTypeCustom];
    [last setImage:[UIImage imageNamed:@"iconfont-suopingshangyiqu"] forState:UIControlStateNormal];
    last.frame  = CGRectMake(_naviBar.center.x - 100, _bofang1.center.y - 20, 40 * WIDTH, 40 *HEIGHT);
    
    [last addTarget:self action:@selector(lastClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.naviBar addSubview:last];
    
    UIButton *next = [ UIButton buttonWithType:UIButtonTypeCustom];
    [next setImage:[UIImage imageNamed:@"iconfont-suopingxiayiqu"] forState:UIControlStateNormal];
    next.frame  = CGRectMake(_naviBar.center.x + 60, _bofang1.center.y -20, 40 * WIDTH, 40 *HEIGHT);
    [next addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.naviBar addSubview:next];

    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(20 * WIDTH, -10, 25 * WIDTH, 25 * WIDTH);
    leftButton.center = CGPointMake(leftButton.center.x, _naviBar.center.y);
    [leftButton setImage:[UIImage imageNamed:@"iconfont-jiantou"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
}
#pragma mark - KVO 观察后执行的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    CGFloat newY = [[change objectForKey:@"new"] CGPointValue].y;
    if (newY > 190) {
        /* tabBar隐藏 */
              [UIView animateWithDuration:0.5 animations:^{
            _naviBar.alpha = 1;
            
        }];
        if (_isPlay) {
            _bofang.selected = NO;
        } else {
            _bofang.selected = YES;
        }
    } else if (newY < 50) {
        /* tabBar出现 */
        if (_isPlay) {
            _bofang1.selected = NO;
        } else {
            _bofang1.selected = YES;
        }
        [UIView animateWithDuration:0.5 animations:^{
            _naviBar.alpha = 0;
        }];
    }
}
-(void)buttonClick
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
